from django.shortcuts import render
from django.views.generic import View
from django.http import JsonResponse

from goods.models import GoodsSKU
from utils.mixin import LoginRequiredMixin
from cart.models import Cart
# Create your views here.

class CartAddView(View):
    def post(self, request):
        user = request.user
        if not user.is_authenticated():
            return JsonResponse({'res':0, 'errmsg':'请先登录'})

        # 接收数据
        print('aaaaaaaaaaaaa')
        print(request.POST.get('sku_id'))
        sku_id = request.POST.get('sku_id')
        count = request.POST.get('count')
        # 数据校验
        if not all([sku_id, count]):
            return JsonResponse({'res': 1, 'errmsg': '数据不完整'})

        # 校验添加的商品数量
        try:
            count = int(count)
        except Exception as e:
            # 数目出错
            return JsonResponse({'res': 2, 'errmsg': '商品数目出错'})

        # 校验商品是否存在
        try:
            sku = GoodsSKU.objects.get(id=sku_id)
        except GoodsSKU.DoesNotExist:
            # 商品不存在
            return JsonResponse({'res': 3, 'errmsg': '商品不存在'})
        # 校验商品的库存
        if count > sku.stock:
            return JsonResponse({'res': 4, 'errmsg': '商品库存不足'})

        try:
            cart = Cart.objects.get(sku=sku)
            cart.count = cart.count + count
        except Cart.DoesNotExist:
            cart = Cart()
            cart.sku = GoodsSKU.objects.get(id=sku_id)
            cart.count = count

        cart.save()
        # 计算用户购物车商品的条目数

        total_count = Cart.objects.all().count()

        # 返回应答
        return JsonResponse({'res': 5, 'total_count': total_count, 'message': '添加成功'})

class CartInfoView(View):
    def get(self, request):
        print('aaaaaa')
        user = request.user
        skus = []
        # 保存用户购物车中商品的总数目和总价格
        total_count = 0
        total_price = 0
        carts = Cart.objects.all()
        print(carts)
        for item in carts:
            # 根据商品的id获取商品的信息
            sku_id = item.sku_id
            print(sku_id)
            sku = GoodsSKU.objects.get(id=item.sku_id)
            # # sku = carts.get(sku=sku)
            amount = sku.price*int(item.count)
            sku.amount = amount
            sku.count = item.count
            skus.append(sku)
            #
            total_count += int(item.count)
            total_price += amount
            # 组织上下文
        context = {'total_count': total_count,
                   'total_price': total_price,
                   'skus': skus}
        return render(request, 'cart.html', context)

# 更新购物车记录
# 采用ajax post请求
# 前端需要传递的参数:商品id(sku_id) 更新的商品数量(count)
# /cart/update
class CartUpdateView(View):
    '''购物车记录更新'''
    def post(self, request):
        '''购物车记录更新'''
        user = request.user
        if not user.is_authenticated():
            # 用户未登录
            return JsonResponse({'res': 0, 'errmsg': '请先登录'})

        # 接收数据
        sku_id = request.POST.get('sku_id')
        count = request.POST.get('count')

        # 数据校验
        if not all([sku_id, count]):
            return JsonResponse({'res': 1, 'errmsg': '数据不完整'})

        # 校验添加的商品数量
        try:
            count = int(count)
        except Exception as e:
            # 数目出错
            return JsonResponse({'res': 2, 'errmsg': '商品数目出错'})

        # 校验商品是否存在
        try:
            sku = GoodsSKU.objects.get(id=sku_id)
        except GoodsSKU.DoesNotExist:
            # 商品不存在
            return JsonResponse({'res': 3, 'errmsg': '商品不存在'})

        # 业务处理:更新购物车记录
        # conn = get_redis_connection('default')
        # cart_key = 'cart_%d'%user.id

        # 校验商品的库存
        if count > sku.stock:
            return JsonResponse({'res':4, 'errmsg':'商品库存不足'})

        # 更新
        # conn.hset(cart_key, sku_id, count)
        cart = Cart.objects.filter(sku=sku)
        cart.update(count=count)
        # 计算用户购物车中商品的总件数 {'1':5, '2':3}
        total_count = 0
        for val in Cart.objects.all():
            total_count += int(val.count)

        # 返回应答
        return JsonResponse({'res':5, 'total_count':total_count, 'message':'更新成功'})

class CartDeleteView(View):
    def post(self, request):
        user = request.user
        if not user.is_authenticated():
            # 用户未登录
            return JsonResponse({'res': 0, 'errmsg': '请先登录'})

        # 接收参数
        sku_id = request.POST.get('sku_id')

        # 数据的校验
        if not sku_id:
            return JsonResponse({'res': 1, 'errmsg': '无效的商品id'})

        # 校验商品是否存在
        try:
            sku = GoodsSKU.objects.get(id=sku_id)
        except GoodsSKU.DoesNotExist:
            # 商品不存在
            return JsonResponse({'res': 2, 'errmsg': '商品不存在'})

        # conn.hset(cart_key, sku_id, count)
        cart = Cart.objects.filter(sku=sku)
        cart.delete()

        # 计算用户购物车中商品的总件数 {'1':5, '2':3}
        total_count = 0
        for val in Cart.objects.all():
            total_count += int(val.count)

        # 返回应答
        return JsonResponse({'res': 3, 'total_count': total_count, 'message': '删除成功'})